<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">





<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="长连接,短连接," />










<meta name="description" content="1、HTTP协议与TCP协议的关系？？HTTP的长连接和短连接实质上是TCP的长连接和短连接。HTTP属于应用层协议，在传输层使用TCP协议，在网络层使用IP协议。">
<meta name="keywords" content="长连接,短连接">
<meta property="og:type" content="article">
<meta property="og:title" content="长连接与短连接">
<meta property="og:url" content="http://yoursite.com/2018/07/14/长连接与短连接/index.html">
<meta property="og:site_name" content="Askunix&#39;s Blog">
<meta property="og:description" content="1、HTTP协议与TCP协议的关系？？HTTP的长连接和短连接实质上是TCP的长连接和短连接。HTTP属于应用层协议，在传输层使用TCP协议，在网络层使用IP协议。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://p9ff104hp.bkt.clouddn.com/%E9%95%BF%E8%BF%9E%E6%8E%A5-%E7%9F%AD%E8%BF%9E%E6%8E%A5.png">
<meta property="og:updated_time" content="2018-07-14T04:00:15.020Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="长连接与短连接">
<meta name="twitter:description" content="1、HTTP协议与TCP协议的关系？？HTTP的长连接和短连接实质上是TCP的长连接和短连接。HTTP属于应用层协议，在传输层使用TCP协议，在网络层使用IP协议。">
<meta name="twitter:image" content="http://p9ff104hp.bkt.clouddn.com/%E9%95%BF%E8%BF%9E%E6%8E%A5-%E7%9F%AD%E8%BF%9E%E6%8E%A5.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/07/14/长连接与短连接/"/>





<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">



<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>










  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "8c28bdbe"
    });
  daovoice('update');
  </script>










  <title>长连接与短连接 | Askunix's Blog</title>
  
  
  
  <head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">





<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="长连接,短连接," />










<meta name="description" content="1、HTTP协议与TCP协议的关系？？HTTP的长连接和短连接实质上是TCP的长连接和短连接。HTTP属于应用层协议，在传输层使用TCP协议，在网络层使用IP协议。">
<meta name="keywords" content="长连接,短连接">
<meta property="og:type" content="article">
<meta property="og:title" content="长连接与短连接">
<meta property="og:url" content="http://yoursite.com/2018/07/14/长连接与短连接/index.html">
<meta property="og:site_name" content="Askunix&#39;s Blog">
<meta property="og:description" content="1、HTTP协议与TCP协议的关系？？HTTP的长连接和短连接实质上是TCP的长连接和短连接。HTTP属于应用层协议，在传输层使用TCP协议，在网络层使用IP协议。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://p9ff104hp.bkt.clouddn.com/%E9%95%BF%E8%BF%9E%E6%8E%A5-%E7%9F%AD%E8%BF%9E%E6%8E%A5.png">
<meta property="og:updated_time" content="2018-07-14T04:00:15.020Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="长连接与短连接">
<meta name="twitter:description" content="1、HTTP协议与TCP协议的关系？？HTTP的长连接和短连接实质上是TCP的长连接和短连接。HTTP属于应用层协议，在传输层使用TCP协议，在网络层使用IP协议。">
<meta name="twitter:image" content="http://p9ff104hp.bkt.clouddn.com/%E9%95%BF%E8%BF%9E%E6%8E%A5-%E7%9F%AD%E8%BF%9E%E6%8E%A5.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/07/14/长连接与短连接/"/>





<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<link href="//cdn.bootcss.com/pace/1.0.2/themes/pink/pace-theme-flash.css" rel="stylesheet">



<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>










  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "8c28bdbe"
    });
  daovoice('update');
  </script>










  <title>长连接与短连接 | Askunix's Blog</title>
  <style>
  .forkme{
 display: none;
 }
  @media (min-width: 768px) {
 .forkme{
 display: inline;
 }
  }
  </style>
</head>


  
  
  
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e788bb7bb12bdeb68dc9923dc5b7a69a";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

	
	
	
	
	
<a href="https://github.com/askunix" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
	
	
	
	
	
	
	
	
	
	
	
	
	
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Askunix's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">不积跬步无以至千里</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            博客首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于作者
          </a>
        </li>
      
        
        <li class="menu-item menu-item-photo">
          <a href="/photo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-camera-retro"></i> <br />
            
            相册分享
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签速查
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            文章分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档记录
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/07/14/长连接与短连接/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="何进鸿">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://7xrvas.com1.z0.glb.clouddn.com/16-4-6/38502140.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Askunix's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">长连接与短连接</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-07-14T11:52:32+08:00">
                2018-07-14
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/SO-Kernal/" itemprop="url" rel="index">
                    <span itemprop="name">SO Kernal</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/07/14/长连接与短连接/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2018/07/14/长连接与短连接/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2018/07/14/长连接与短连接/" class="leancloud_visitors" data-flag-title="长连接与短连接">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读量&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             <span></span>
			 </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,867
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  6
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="http://p9ff104hp.bkt.clouddn.com/%E9%95%BF%E8%BF%9E%E6%8E%A5-%E7%9F%AD%E8%BF%9E%E6%8E%A5.png" alt=""></p>
<h5 id="1、HTTP协议与TCP协议的关系？？"><a href="#1、HTTP协议与TCP协议的关系？？" class="headerlink" title="1、HTTP协议与TCP协议的关系？？"></a>1、HTTP协议与TCP协议的关系？？</h5><p>HTTP的长连接和短连接实质上是TCP的长连接和短连接。HTTP属于应用层协议，在传输层使用TCP协议，在网络层使用IP协议。</p>
<hr>
<a id="more"></a>
<p>IP层：解决网络路由和寻址问题<br>TCP协议：解决如何在IP层之上可靠的传输数据报，并在另一端收到发送的包，并且顺序与发出顺序一致。TCP有可靠，面向连接特点。</p>
<hr>
<h5 id="2、如何理解HTTP协议是无状态的？？"><a href="#2、如何理解HTTP协议是无状态的？？" class="headerlink" title="2、如何理解HTTP协议是无状态的？？"></a>2、如何理解HTTP协议是无状态的？？</h5><p>无状态指的是协议对事务处理没有记忆能力，服务器不知道客户端是什么状态。也就是说，打开一个服务器网页和你之前打开它之间没有任何联系。</p>
<p>HTTP是一个无状态的面向连接的协议，无状态不代表HTTP不能保持TCP连接，更不能代表HTTP使用的是UDP协议（无连接协议）。</p>
<hr>
<h5 id="3、什么是长连接、短连接？？"><a href="#3、什么是长连接、短连接？？" class="headerlink" title="3、什么是长连接、短连接？？"></a>3、什么是长连接、短连接？？</h5><p>在HTTP/1.0 中，默认使用短连接。<br>就是说：浏览器和服务器每进行一次HTTP操作，就建立一次连接，但任务结束就中断连接。</p>
<p>如果客户端浏览器访问某个HTML或者其他类型的Web页面中包含其他Web资源的这种情况，<br>如：JavaScript文件、图像文件、CSS文件等，浏览器遇到这样的Web资源，就会建立一个会话。</p>
<p>从 HTTP/1.1 起，默认使用长连接，保持连接持续性。<br>一个网页打开完成后，客户端和服务器之间用于传输HTTP数据的TCP连接不会关闭，如果客户端再次访问这个服务器上的的网页，<br>会继续使用这一条已经建立好的连接。</p>
<p>Keep-Alive不会永久保持连接，它有一个保持的时间，可以在不同服务器软件中设定这个时间（Apache）。<br>要实现长连接，客户端、服务器端首先得支持。</p>
<p>HTTP协议长连接、短连接实质上是TCP协议的长连接、短连接。</p>
<h6 id="TCP短连接"><a href="#TCP短连接" class="headerlink" title="TCP短连接"></a>TCP短连接</h6><p>模拟一下TCP短连接的情况，Client向server发起连接请求，server接到请求，然后双方建立连接，Client向server发送消息，<br>server回应client，然后一次读写就完成了，这是双方任意一放都可以发起close请求。一般都是client发起close请求。</p>
<ul>
<li>短连接优点：</li>
</ul>
<p>管理起来简单，存在的连接都是有用的，不需要额外的控制手段。</p>
<h6 id="TCP长连接"><a href="#TCP长连接" class="headerlink" title="TCP长连接"></a>TCP长连接</h6><p>模拟TCP长连接情况：client向server发送连接请求，server接受client连接，双方建立连接，client与server完成一次读写之后，<br>他们并不会主动关闭，后续的读写操作会继续使用这个连接。</p>
<p>首先说一下TCP/IP上说到的TCP保活功能，保活功能主要为服务器应用提供，服务器应用希望知道客户端主机是否崩溃，<br>从而可以代表客户使用资源。如果客户已经消失，使得服务器上保留一半开放的连接，而服务器又在等待来自客户端的数据，<br>保活功能就是试图在服务器端检测这种半开放的连接。</p>
<p>如果给定的连接在两个小时内没有任何的动作，则服务器就向客户端发送一个探测报文段，</p>
<p>客户端必须处于以下四种转态。</p>
<p>1、客户端主机依然正常运行，并从服务器可达，客户的TCP响应正常，而服务器也知道对方是正常的，服务器在两小时之后将保活计时器复位。</p>
<p>2、客户端已经崩溃，并且关闭或者正在重启。在任何一种情况下，客户端的TCP都没有响应，那么服务器端也就不能收到探测响应。<br>并在75秒后超时，服务器共发送10个这样的探测，每个间隔75秒，如果客户端没有收到一个响应，就认为客户端主机已经关闭并终止连接。</p>
<p>3、客户端主机已经崩溃，但是已经重新启动。服务器将收到一个对其保活探测的响应，这个响应是一个复位，使得服务器终止这个连接。</p>
<p>4、客户端正常运行，但服务器不可达，类似2.TCP能发现的就是没有收到的响应。</p>
<h5 id="短连接步骤："><a href="#短连接步骤：" class="headerlink" title="短连接步骤："></a>短连接步骤：</h5><p>建立连接–数据传输–关闭连接 ——</p>
<h5 id="长连接步骤："><a href="#长连接步骤：" class="headerlink" title="长连接步骤："></a>长连接步骤：</h5><p>建立连接–数据传输–（保持连接）–数据传输–数据传输–关闭连接 ——</p>
<hr>
<h5 id="4、长连接和短连接的优缺点？？"><a href="#4、长连接和短连接的优缺点？？" class="headerlink" title="4、长连接和短连接的优缺点？？"></a>4、长连接和短连接的优缺点？？</h5><p>由上可知，长连接省去了较多的TCP建立、关闭操作，减少了浪费，节约时间。对于频繁请求资源的客户来说，适合用长连接。<br>不过保活功能探测周期比较长，而且只能探测TCP连接的存活，遇到恶意连接，保活功能就有点不够用了。</p>
<p>在长连接的应用场景下，client端一般不会主动关闭它们之间的连接，Client与server之间的连接如果一直不关闭的话，会存在一个问题，随着客户端连接越来越多，server早晚有扛不住的时候，这时候server端需要采取一些策略，如关闭一些长时间没有读写事件发生的连接，这样可 以避免一些恶意连接导致server端服务受损；如果条件再允许就可以以客户端机器为颗粒度，限制每个客户端的最大长连接数，这样可以完全避免某个蛋疼的客户端连累后端服务。</p>
<p>短连接对于服务器来说管理较为简单，存在的连接都是有用的连接，不需要额外的控制手段。但如果客户请求频繁，将在TCP的建立和关闭操作上浪费时间和带宽。</p>
<p>长连接和短连接的产生在于client和server采取的关闭策略，具体的应用场景采用具体的策略，没有十全十美的选择，只有合适的选择。</p>
<hr>
<h5 id="5-什么时候用长连接，短连接？"><a href="#5-什么时候用长连接，短连接？" class="headerlink" title="5. 什么时候用长连接，短连接？"></a>5. 什么时候用长连接，短连接？</h5><p>长连接多用于操作频繁，点对点的通讯，而且连接数不能太多情况，每个TCP连接都需要三步握手，这需要时间，如果每个操作都是先连接，再操作的话那么处理速度会降低很多，所以每个操作完后都不断开，次处理时直接发送数据包就OK了，不用建立TCP连接。</p>
<p>例如：数据库的连接用长连接， 如果用短连接频繁的通信会造成socket错误，而且频繁的socket 创建也是对资源的浪费。</p>
<p>而像WEB网站的http服务一般都用短链接，因为长连接对于服务端来说会耗费一定的资源，而像WEB网站这么频繁的成千上万甚至上亿客户端的连接用短连接会更省一些资源。</p>
<p>如果用长连接而且同时有成千上万的用户，如果每个用户都占用一个连接的话，那可想而知吧。所以并发量大，但每个用户无需频繁操作情况下需用短连好。</p>

      
    </div>
    
    
    
	
	
	
	<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>


  
</div>
	
	

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/money.png" alt="何进鸿 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/长连接/" rel="tag"><i class="fa fa-tag"></i> 长连接</a>
          
            <a href="/tags/短连接/" rel="tag"><i class="fa fa-tag"></i> 短连接</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/06/21/【编程之美】链表面试题汇总版/" rel="next" title="【编程之美】链表面试题汇总版">
                <i class="fa fa-chevron-left"></i> 【编程之美】链表面试题汇总版
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="http://7xrvas.com1.z0.glb.clouddn.com/16-4-6/38502140.jpg"
                alt="何进鸿" />
            
              <p class="site-author-name" itemprop="name">何进鸿</p>
              <p class="site-description motion-element" itemprop="description">技术汇总、趣事速记</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/m0_37925202" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-skype"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:askunix@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5729154534/profile?topnav=1&wvr=6" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/timeline" target="_blank" title="JueJin">
                      
                        <i class="fa fa-fw fa-magnet"></i>JueJin</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/yourname" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://youtube.com/yourname" target="_blank" title="YouTube">
                      
                        <i class="fa fa-fw fa-youtube"></i>YouTube</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.runoob.com/" title="RUNOOB.COM" target="_blank">RUNOOB.COM</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.liaoxuefeng.com/category/0013738748415562fee26e070fa4664ad926c8e30146c67000" title="寥雪峰的官方网站" target="_blank">寥雪峰的官方网站</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.csdn.net/m0_37925202" title="say_askunix的博客" target="_blank">say_askunix的博客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://iissnan.com/progit/" title="Pro Git简体中文版" target="_blank">Pro Git简体中文版</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.bootcss.com/p/font-awesome/#" title="Font Awesome" target="_blank">Font Awesome</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://ju.outofmemory.cn/" title="聚客·汇聚优秀技术" target="_blank">聚客·汇聚优秀技术</a>
                  </li>
                
              </ul>
            </div>
          

		  
		  
		  
		  
		<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=528478901&auto=0&height=66"></iframe>  
		  
		  
		  
		  
		  
		  
		  
		  
		  
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-5"><a class="nav-link" href="#1、HTTP协议与TCP协议的关系？？"><span class="nav-number">1.</span> <span class="nav-text">1、HTTP协议与TCP协议的关系？？</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2、如何理解HTTP协议是无状态的？？"><span class="nav-number">2.</span> <span class="nav-text">2、如何理解HTTP协议是无状态的？？</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3、什么是长连接、短连接？？"><span class="nav-number">3.</span> <span class="nav-text">3、什么是长连接、短连接？？</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#TCP短连接"><span class="nav-number">3.1.</span> <span class="nav-text">TCP短连接</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#TCP长连接"><span class="nav-number">3.2.</span> <span class="nav-text">TCP长连接</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#短连接步骤："><span class="nav-number">4.</span> <span class="nav-text">短连接步骤：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#长连接步骤："><span class="nav-number">5.</span> <span class="nav-text">长连接步骤：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4、长连接和短连接的优缺点？？"><span class="nav-number">6.</span> <span class="nav-text">4、长连接和短连接的优缺点？？</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#5-什么时候用长连接，短连接？"><span class="nav-number">7.</span> <span class="nav-text">5. 什么时候用长连接，短连接？</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        

<div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">何进鸿</span>

  
</div>



<!--
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>

-->







<div class="theme-info">
  <div class="powered-by"></div>
   <i class="fa fa-pencil"></i>
  <span class="post-count">全站共13.1k字</span>
</div>






|| 梦想没了行动  只会变成空想 || 建议PC端浏览
 
 



 
 
 <div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

本站总访问量 <span id="busuanzi_value_site_pv"></span> 次&nbsp&nbsp&nbsp
本站访客数<span id="busuanzi_value_site_uv"></span>人次



</div>

 
 
 
 
 
<!--
<div class="powered-by"></div>
	
    <span class="site-uv">
      <i class="fa fa-eye"></i>
	  
      全站访客<span class="busuanzi-value" id="busuanzi_value_site_pv"></span> 次</span>

-->



<!-- 新增访客统计代码 -->
<!--
<div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-balance-scale"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">何进鸿</span>
</div>


<div class="busuanzi-count">
    <script async="" src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="site-uv">
      <i class="fa fa-user"></i>
      访问用户： <span class="busuanzi-value" id="busuanzi_value_site_uv"></span> 人
    </span>
	
-->
	
<!--	
    <div class="powered-by"></div>
	
    <span class="site-uv">
      <i class="fa fa-eye"></i>
	  
      全站访客： <span class="busuanzi-value" id="busuanzi_value_site_pv"></span> 次</span>
-->	
	

	
<!-- 博客字数统计 
    <span class="site-pv">
      <i class="fa fa-pencil"></i>
      全站共： <span class="post-count">13.1k</span> 字
    </span>
</div>
-->
<!-- 新增访客统计代码 END-->



<section class="footer-time">
    <span class="footer__copyright">
    <div>
    <span id="span_dt_dt"> </span>
    <script language="javascript">
      function show_date_time(){
        window.setTimeout("show_date_time()", 1000);
        BirthDay=new Date("6/25/2018 10:56:12");
        today=new Date();
        timeold=(today.getTime()-BirthDay.getTime());
        sectimeold=timeold/1000
        secondsold=Math.floor(sectimeold);
        msPerDay=24*60*60*1000
        e_daysold=timeold/msPerDay
        daysold=Math.floor(e_daysold);
        e_hrsold=(e_daysold-daysold)*24;
        hrsold=Math.floor(e_hrsold);
        e_minsold=(e_hrsold-hrsold)*60;
        minsold=Math.floor((e_hrsold-hrsold)*60);
        seconds=Math.floor((e_minsold-minsold)*60);
        span_dt_dt.innerHTML="Askunix's Blog已运行："+daysold+" 天 "+hrsold+" 小时 "+minsold+" 分 "+seconds+" 秒";
      }
      show_date_time();
    </script>
    </div>
    <script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
</section>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '8rbOzLF6j6mMuBvuRBuOLq5O-gzGzoHsz',
        appKey: '4PbGi909IHAsoIarzl5ryvrA',
        placeholder: '来啊，快活啊~',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("O8NSjM7KSnPoDYSlBbd2lqfX-gzGzoHsz", "19z7omdx78LwKxzBHxrOskhe");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

  
  
  <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
  
  

  
  
  
 
<script type="text/javascript"
color="0,0,255" opacity='0.7' zIndex="-2" count="99" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>

  
  
  
  
  
</body>
</html>
